<template>
  <div class="deliver-dialog">
    <el-dialog
      ref="deliverDialog"
      :title="title"
      :visible.sync="visible"
      @close="$emit('update:show', false)"
      :show="show"
      width="1367px"
      class="edit-form handle-box"
    >
      <div>
        <el-container class="handle-box">
          <tabs
            :tabs-arr="tabArr"
            @returnIndex="handletabs" />
          <!-- 列表 -->
          <el-header
            height="auto"
            class="topfrom">
            <el-form
              ref="form"
              :model="handleFormData"
              label-width="120px">
              <el-form-item label="扫描条码">
                <el-input
                  ref="qrcodeInput"
                  v-model="handleFormData.barcode"
                  @change="inputChange"
                  placeholder="解码信息：此处显示扫码解析出的解码信息"
                />
              </el-form-item>
            </el-form>
            <div v-if="isShowBtn">
              <el-button
                type="primary"
                class="import-btn"
                @click="handleImportDeliverGoodsDetail"
              >导入发货物品</el-button>
              <el-button
                type="text"
                class="add-btn"
                @click="handleDownloadTemplate">下载发货导入模板.cvs</el-button>
            </div>
          </el-header>
          <el-editable
            class="dialog-table-box"
            :data="currentSelectedData"
            height="200"
            :columns="dialogtableColumns"
          >
            <template
              slot="default-sweepCount"
              slot-scope="{row}"
            >{{ `${Number(totalScanCount)}/${row.awaitSendNum?row.awaitSendNum:0}${row.unit?row.unit:''}` }}</template>
          </el-editable>
        </el-container>
        <div class="add-title">
          <h3 class="dialog-detail-title">物品详情</h3>
          <el-button
            class="add-row-btn"
            size="mini"
            @click.stop="addEmptyRow"
            type="primary">添加</el-button>
        </div>

        <!-- --------------------------------- -->
        <el-editable
          class="product-detail-table-box"
          :data="itemList"
          height="200"
          :columns="itemColumns"
        >
          <template
            slot="default-udi"
            slot-scope="{row,$index}">
            <el-tooltip
              effect="dark"
              :content="row.udi"
              placement="top">
              <el-input
                v-model="row.udi"
                placeholder="请输入" />
            </el-tooltip>
          </template>
          <template
            slot="default-mainCode"
            slot-scope="{row,$index}">
            <el-tooltip
              effect="dark"
              :content="row.mainCode"
              placement="top">
              <el-input
                v-model="row.mainCode"
                placeholder="请输入" />
            </el-tooltip>
          </template>
          <template
            slot="default-batchNo"
            slot-scope="{row,$index}">
            <el-input
              v-if="row.hasOwnProperty('productBatch')"
              v-model="row.productBatch"
              placeholder="请输入"
            />
            <el-input
              v-else
              v-model="row.batchNo"
              placeholder="请输入" />
          </template>
          <template
            slot-scope="{row,$index}"
            slot="default-productDate">
            <el-date-picker
              style="width:160px;"
              v-model="row.productDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </template>
          <template
            slot-scope="{row,$index}"
            slot="default-expDate">
            <el-date-picker
              style="width:160px;"
              v-model="row.expDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </template>
          <template
            slot="default-serialNo"
            slot-scope="{row,$index}">
            <el-input
              v-model="row.serialNo"
              placeholder="请输入" />
          </template>
          <template
            slot="default-num"
            slot-scope="{row}">
            <el-input
              type="number"
              v-model.number="row.num"
              placeholder="请输入"
            />
          </template>
          <template
            slot="default-action"
            slot-scope="scope">
            <!-- <el-button
              v-if="itemList.length === Number(scope.$index) + 1"
              size="small"
              @click.stop="addEmptyRow(scope.row,scope.$index)"
            type="text text-primary">添加</el-button>-->
            <el-button
              size="small"
              @click.stop="deleteTableRow(scope.$index)"
              type="text text-danger"
            >删除</el-button>
          </template>
        </el-editable>
        <!-- ---------------------------------------- -->
      </div>
      <div>
        <div class="button-box">
          <el-button
            class="submission"
            :loading="submitLoading"
            @click="onSubmit">确定</el-button>
          <el-button
            class="cancel-dialog"
            @click="visible=false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { isObject, cloneDeep, hasIn } from 'lodash'
import { TAB_ARR, DIALOG_TABLE_COLUMNS, ITEM_COLUMNS } from './const.js'
import ElEditable from '@components/el-editable/index.vue'
import tabs from '@components/tabs/index.vue'
import { scanItemInfo } from '@const/prdutCentApi'

export default {
  name: 'DeliverDialog',
  components: { ElEditable, tabs },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    isShowBtn: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '添加发货物品'
    },
    currentSelectedData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      tabArr: TAB_ARR,
      visible: this.show,
      isEdit: false,
      handleFormData: {
        barcode: ''
      },
      dialogtableColumns: DIALOG_TABLE_COLUMNS,
      itemColumns: ITEM_COLUMNS, // 物品详情表头
      itemList: [], // 物品详情列表
      submitLoading: false,
      longBarcode: false, // 长短码标志长码true 短码false
      countFlag: 0,
      mainCode: '', // 主条码
      secondCode: '' // 附属条码
    }
  },
  computed: {
    productItemId () {
      return this.currentSelectedData[0].comProdItemId // todo 需要确认平台产品id字段是哪个
    },
    totalScanCount () {
      let total = 0
      let data = this.itemList || []
      data.forEach((item, index) => {
        if (item.num) {
          total += item.num
        }
      })
      return total
    }
  },
  watch: {
    show (status) {
      this.visible = this.show
      let data = this.itemList || []
      // data = this.currentSelectedData[0].distributorList// 打开弹窗获取物品详情列表
      // 判断distributorList有没有数据
      if (this.currentSelectedData[0].distributorList.length === 0) {
        this.itemList = []
      } else {
        this.itemList = cloneDeep(this.currentSelectedData[0].distributorList)
      }
      if (status) {
        this.$nextTick(() => {
          this.handleFormData.barcode = ''
          this.$refs.qrcodeInput.focus()
        })
      }
    },
    'handleFormData.barcode': {
      handler (nv, ov) {
        if (nv) {
          this.inputChange(nv)
        }
      }
    }
  },
  methods: {
    handletabs (index) {
      this.$refs.qrcodeInput.focus()
      if (index === 0) {
        this.longBarcode = false
        // 每次选择短码时，重置countFlag
        this.countFlag = 0
      } else {
        this.longBarcode = true
      }
      this.handleFormData.barcode = ''
    },
    // 根据扫码得到的数据查询接口，得到数据后添加到table列
    inputChange (val) {
      if (this.longBarcode) {
        this.mainCode = val
        this.secondCode = ''
      } else {
        // 若为短码时，由于要输入两次，所以设置一个flag计数器
        // 若countFlag为0，则设置主条码，否则设置附属条码
        if (this.countFlag === 0) {
          this.mainCode = val
          this.countFlag++
        } else {
          this.secondCode = val
        }
      }
      this.getItemInfo(val)
    },
    getItemInfo (val) {
      const postData = {
        productItemId: this.productItemId,
        longBarcode: this.longBarcode,
        mainCode: this.mainCode,
        secondCode: this.secondCode
      }
      this.$axios
        .$post(scanItemInfo, postData)
        .then(res => {
          if (!res.payload) {
            // 如果没有返回信息就继续扫
            this.handleFormData.barcode = ''
            this.$refs.qrcodeInput.focus()
          } else {
            // 有返回，就将信息填充到表格中
            const itemInfo = res.payload
            const item = {
              ...itemInfo,
              num: 1,
              productBatch: itemInfo.batchNo
            }
            // 这里需要做下逻辑判断，如果是重复的数据，则找到该数据，给数量加一，否则，加入到数组中
            if (this.itemList.length > 0) {
              this.itemList.forEach(it => {
                if (
                  it.batchNo === item.batchNo &&
                  it.mainCode === item.mainCode &&
                  it.productBatch === item.productBatch &&
                  it.productDate === item.productDate &&
                  it.serialNo === item.serialNo &&
                  it.udi === item.udi &&
                  it.expDate === item.expDate
                ) {
                  it.num += 1
                } else {
                  this.itemList.push(item)
                }
              })
            } else {
              this.itemList.push(item)
            }
            // 如果获取到了正确数据，那么清空所有字段
            this.handleFormData.barcode = ''
            this.mainCode = ''
            this.secondCode = ''
            this.countFlag = 0
          }
        })
        .catch(e => {
          // 如果报错
          this.handleFormData.barcode = ''
          this.$refs.qrcodeInput.focus()
          this.mainCode = ''
          this.secondCode = ''
          // 且重置countFlag
          this.countFlag = 0
        })
        .finally(() => {})
    },
    onSubmit () {
      let index = 0
      this.itemList.forEach(item => {
        if (
          !item.productBatch ||
          !item.productDate ||
          !item.expDate ||
          !item.num
        ) {
          index++
        }
      })
      if (index !== 0) {
        this.$message({
          message: '请填写完整信息！',
          type: 'warning',
          duration: '800'
        })
        return false
      }

      const submitItems = [...this.itemList]

      this.$emit('submitDialog', this.totalScanCount, submitItems)
      console.log(submitItems)
    },
    addEmptyRow () {
      this.itemList.push({
        productBatch: '',
        udi: '',
        barCode: '',
        productDate: '',
        expDate: '',
        serialNo: '',
        num: 0
      })
    },
    deleteTableRow (index) {
      this.itemList.splice(index, 1)
    },
    // 导入发货物品
    handleImportDeliverGoodsDetail () {
      this.$emit('importDeliverGoods')
    },
    // 下载模板
    handleDownloadTemplate () {
      this.$emit('downloadTemplate')
    }
  }
}
</script>

<style lang="less">
.deliver-dialog {
  .handle-box {
    .dialog-table-box {
      margin-bottom: 20px;
    }

    .button-box {
      width: 167px;
      margin: 20px auto;
    }

    .submission {
      background: rgba(35, 113, 197, 1);
      border: 0;
      color: #fff;
      margin-bottom: 10px;
    }

    .topfrom {
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      .el-form-item {
        display: inline-block;
      }

      .el-input {
        width: 297px;
      }
    }
  }

  .add-row-btn {
    margin: 0 0 12px 16px;
  }

  .dialog-detail-title {
    padding: 0 0 16px 16px;
  }

  .product-detail-table-box {
    .has-gutter {
      .editable-header-cell-class:nth-child(4),
      .editable-header-cell-class:nth-child(5),
      .editable-header-cell-class:nth-child(6),
      .editable-header-cell-class:nth-child(8) {
        position: relative;
        // color: red;
        ::before {
          position: absolute;
          content: '*';
          color: red;
          top: 0;
          left: 0;
        }
      }
    }

    .table-item {
      display: inline-block;
      width: 120px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      vertical-align: middle;
    }
  }
  //去掉输入的的上下可加减数量的小三角
  input[type='number'] {
    -moz-appearance: textfield;
  }

  input[type='number']::-webkit-inner-spin-button,
  input[type='number']::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
  .add-title {
    display: flex;
    justify-content: space-between;
  }
}
</style>
